import { useState, useEffect, useCallback } from "react";
import { Button, Input, List, Upload, Space, Tag, Modal } from "antd";
import { message } from "../../utils/customMessage";
import {
  UploadOutlined,
  SearchOutlined,
  ClearOutlined,
  DownloadOutlined,
  EyeOutlined,
  DeleteOutlined,
} from "@ant-design/icons";
import type { UploadProps } from "antd";
import type { RcFile } from "antd/es/upload/interface";
import FilePreview from "../components/filePreview";
import { useLocation } from "react-router-dom";
import { http } from "../../utils/request";

interface FileItem {
  id: number;
  fileName: string;
  filePath: string;
  fileUrl: string | null;
  updateTime: string;
  fileContent: string;
}

const Common = () => {
  const [searchValue, setSearchValue] = useState("");
  const [fileList, setFileList] = useState<FileItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [userInfo, setUserInfo] = useState<any>(null);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [uploading, setUploading] = useState(false);
  const [uploadingMultiple, setUploadingMultiple] = useState(false);
  const [folderModalVisible, setFolderModalVisible] = useState(false);
  const [folderPath, setFolderPath] = useState("");
  const [previewVisible, setPreviewVisible] = useState(false);
  const [previewFile, setPreviewFile] = useState<FileItem | null>(null);
  const [selectedFiles, setSelectedFiles] = useState<RcFile[]>([]);
  const [uploadKey, setUploadKey] = useState(0);
  const [contentModalVisible, setContentModalVisible] = useState(false);
  const [currentFileContent, setCurrentFileContent] = useState<string>("");
  const [currentFileName, setCurrentFileName] = useState<string>("");
  const location = useLocation();

  // 获取用户信息的函数
  const fetchUserInfo = async () => {
    try {
      const userId = localStorage.getItem("userId");

      if (!userId) {
        message.error("未找到用户ID");
        return;
      }

      const result = await http.get(`/api/user/userInfo?id=${userId}`);

      if (+result.status === 200 && result.data) {
        setUserInfo(result.data);
        localStorage.setItem("userInfo", JSON.stringify(result.data));
      } else {
        message.error(result.message || "获取用户信息失败");
      }
    } catch (error) {
      message.error("获取用户信息失败");
    }
  };

  // 获取 menuId 的函数
  const getMenuId = (path: string): number | null => {
    try {
      const findMenuId = (menus: any[]): number | null => {
        for (const menu of menus) {
          if (menu.url === path) {
            return menu.id;
          }
          const children = menu.menuList || menu.children;
          if (children && children.length > 0) {
            const found = findMenuId(children);
            if (found) return found;
          }
        }
        return null;
      };

      return findMenuId(userInfo.role.menuList);
    } catch (error) {
      return null;
    }
  };

  // 获取页面标题
  const getPageTitle = (path: string): string => {
    if (!userInfo?.role?.menuList) return "页面";

    try {
      const findTitle = (menus: any[]): string => {
        for (const menu of menus) {
          if (menu.url === path) {
            return menu.menuName;
          }
          const children = menu.menuList || menu.children;
          if (children && children.length > 0) {
            const found = findTitle(children);
            if (found) return found;
          }
        }
        return "页面";
      };

      return findTitle(userInfo.role.menuList);
    } catch (error) {
      return "页面";
    }
  };

  // 获取文件列表
  const fetchFileList = useCallback(async () => {
    if (!userInfo) return;

    try {
      setLoading(true);
      const currentPath = location.pathname;
      const menuId = getMenuId(currentPath);

      if (!menuId) {
        console.log("当前页面没有对应的菜单ID，可能是通用页面");
        setFileList([]);
        return;
      }

      const result = await http.get(
        `/api/uploadFile/getFileList?menuId=${menuId}`
      );

      if (+result.status === 200) {
        setFileList(result.data);
      } else {
        message.error(result.message || "获取文件列表失败");
      }
    } catch (error) {
      message.error("获取文件列表失败");
    } finally {
      setLoading(false);
    }
  }, [userInfo, location.pathname]);

  // 组件加载时获取用户信息
  useEffect(() => {
    fetchUserInfo();
  }, []);

  // 当路由变化时，重置文件选择状态
  useEffect(() => {
    setSelectedFiles([]);
    setUploadKey((prev) => prev + 1);
  }, [location.pathname]);

  // 当用户信息获取后，加载文件列表
  useEffect(() => {
    if (userInfo) {
      fetchFileList();
    }
  }, [userInfo, fetchFileList]);

  // 处理单文件上传
  const handleUpload: UploadProps["customRequest"] = async ({ file }) => {
    if (!file) {
      message.error("请选择要上传的文件");
      return;
    }

    const formData = new FormData();
    formData.append("file", file as RcFile);
    formData.append("path", location.pathname);

    try {
      setUploading(true);
      const result = await http.post("/api/uploadFile/uploadFile", formData);

      if (+result.status === 200) {
        message.success("上传成功");
        await fetchFileList();
      } else {
        message.error(result.message || "上传失败");
      }
    } catch (error) {
      message.error("上传失败");
    } finally {
      setUploading(false);
    }
  };

  // 处理多文件选择
  const handleMultipleFileSelect: UploadProps["beforeUpload"] = (
    file,
    fileList
  ) => {
    // 阻止默认上传，只收集文件
    setSelectedFiles(fileList);
    return false;
  };

  // 处理批量上传
  const handleBatchUpload = async () => {
    if (selectedFiles.length === 0) {
      message.warning("请先选择要上传的文件");
      return;
    }

    try {
      setUploadingMultiple(true);

      const formData = new FormData();

      // 将所有文件添加到 FormData 中，形成 files 数组
      selectedFiles.forEach((file) => {
        formData.append("files", file);
      });

      // 添加菜单ID参数
      const menuId = getMenuId(location.pathname);
      if (menuId) {
        formData.append("menuId", menuId.toString());
      }

      const result = await http.post("/api/uploadFile/uploadFolder", formData);

      if (+result.status === 200) {
        message.success(`批量上传成功！共上传 ${selectedFiles.length} 个文件`);
        await fetchFileList(); // 刷新文件列表
        setSelectedFiles([]); // 清空已选文件
        setUploadKey((prev) => prev + 1); // 重置 Upload 组件
      } else {
        message.error(result.message || "批量上传失败");
      }
    } catch (error) {
      console.error("批量上传失败:", error);
      message.error("批量上传失败");
    } finally {
      setUploadingMultiple(false);
    }
  };

  // 处理文件列表变化
  const handleFileListChange: UploadProps["onChange"] = (info) => {
    const { fileList } = info;
    // 过滤掉无效的文件对象
    const validFiles = fileList
      .map((file) => file.originFileObj as RcFile)
      .filter(Boolean);
    setSelectedFiles(validFiles);
  };

  // 清空已选文件
  const handleClearSelectedFiles = () => {
    setSelectedFiles([]);
    setUploadKey((prev) => prev + 1); // 重置 Upload 组件
  };

  // 处理搜索
  const handleSearch = async () => {
    if (!searchValue.trim()) {
      message.warning("请输入搜索关键词");
      return;
    }

    try {
      setLoading(true);
      const { current, pageSize } = pagination;

      // 获取当前菜单ID
      const currentPath = location.pathname;
      const menuId = getMenuId(currentPath);

      if (!menuId) {
        message.error("获取菜单ID失败");
        return;
      }

      const result = await http.get(
        `/api/uploadFile/searchFile?searchContent=${searchValue}&menuId=${menuId}&page=${current}&pageSize=${pageSize}`
      );

      if (+result.status === 200) {
        setFileList(result.data.records);
        setPagination({
          ...pagination,
          total: result.data.total,
        });
      } else {
        message.error(result.message || "搜索失败");
      }
    } catch (error) {
      message.error("搜索失败");
    } finally {
      setLoading(false);
    }
  };

  // 处理清空
  const handleClear = () => {
    setSearchValue("");
    if (userInfo) {
      fetchFileList();
    }
  };

  // 修改下载处理函数
  const handleDownload = (item: FileItem) => {
    if (!item.fileUrl) {
      message.error("文件地址不存在");
      return;
    }

    // 创建一个隐藏的 a 标签来下载文件
    const link = document.createElement("a");
    link.href = item.fileUrl;
    link.download = item.fileName; // 使用文件名作为下载文件名
    link.target = "_blank"; // 在新标签页打开
    link.rel = "noopener noreferrer"; // 安全属性
    link.style.display = "none"; // 隐藏链接
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  // 修改预览处理函数，传递搜索关键字
  const handlePreview = (item: FileItem) => {
    console.log(item, "item111");
    setPreviewFile(item);
    setPreviewVisible(true);
  };

  // 处理预览文件内容
  const handlePreviewContent = (item: FileItem) => {
    setCurrentFileContent(item.fileContent || "暂无内容");
    setCurrentFileName(item.fileName);
    setContentModalVisible(true);
  };

  // 获取文件类型标签颜色
  const getFileTypeColor = (type: string): string => {
    const typeMap: Record<string, string> = {
      xlsx: "green",
      xls: "green",
      doc: "blue",
      docx: "blue",
      pdf: "red",
      txt: "default",
    };
    return typeMap[type.toLowerCase()] || "default";
  };

  // 添加删除处理函数
  const handleDelete = async (fileId: number) => {
    try {
      const result = await http.post(`/api/uploadFile/deleteFile/${fileId}`);

      if (+result.status === 200) {
        message.success("删除成功");
        fetchFileList();
      } else {
        message.error(result.message || "删除失败");
      }
    } catch (error) {
      message.error("删除失败");
    }
  };

  // 处理文件夹上传弹窗
  const handleFolderUploadClick = () => {
    setFolderModalVisible(true);
    setFolderPath(""); // 清空输入框
  };

  // 处理文件夹上传确认
  const handleFolderUploadConfirm = async () => {
    if (!folderPath.trim()) {
      message.warning("请输入文件夹地址");
      return;
    }

    try {
      setUploadingMultiple(true);

      const result = await http.get(
        `/api/uploadFile/uploadFolder?path=${folderPath.trim()}&menuId=${getMenuId(
          location.pathname
        )}`
      );

      if (+result.status === 200) {
        message.success("文件夹上传成功");
        await fetchFileList(); // 刷新文件列表
        setFolderModalVisible(false);
        setFolderPath("");
      } else {
        message.error(result.message || "文件夹上传失败");
      }
    } catch (error) {
      message.error("文件夹上传失败");
    } finally {
      setUploadingMultiple(false);
    }
  };

  // 处理文件夹上传取消
  const handleFolderUploadCancel = () => {
    setFolderModalVisible(false);
    setFolderPath("");
  };

  return (
    <div style={{ padding: "20px" }}>
      {/* 显示当前页面标题 */}
      <div style={{ marginBottom: "16px" }}>
        <h2>{getPageTitle(location.pathname)}</h2>
      </div>

      {/* 搜索区域 */}
      <div
        style={{
          display: "flex",
          alignItems: "center",
          marginBottom: "20px",
          gap: "16px",
        }}
      >
        <Upload
          customRequest={handleUpload}
          showUploadList={false}
          accept="*/*"
          disabled={uploading || uploadingMultiple}
        >
          <Button
            icon={<UploadOutlined />}
            loading={uploading}
            disabled={uploading || uploadingMultiple}
          >
            上传文件
          </Button>
        </Upload>

        <Upload
          key={`multiple-upload-${uploadKey}`}
          multiple
          beforeUpload={handleMultipleFileSelect}
          onChange={handleFileListChange}
          showUploadList={false}
          accept="*/*"
          disabled={uploading || uploadingMultiple}
          fileList={[]}
        >
          <Button
            icon={<UploadOutlined />}
            disabled={uploading || uploadingMultiple}
          >
            选择多个文件
          </Button>
        </Upload>

        {selectedFiles.length > 0 && (
          <>
            <Button
              type="primary"
              loading={uploadingMultiple}
              disabled={uploading || uploadingMultiple}
              onClick={handleBatchUpload}
            >
              批量上传 ({selectedFiles.length}个文件)
            </Button>
            <Button
              onClick={handleClearSelectedFiles}
              disabled={uploading || uploadingMultiple}
            >
              清空选择
            </Button>
          </>
        )}
        <div
          style={{
            flex: 1,
            display: "flex",
            gap: "8px",
            maxWidth: "800px",
            margin: "0 auto",
          }}
        >
          <Input
            placeholder="请输入搜索关键词"
            value={searchValue}
            onChange={(e) => setSearchValue(e.target.value)}
            onPressEnter={handleSearch}
            style={{ width: "100%" }}
          />
          <Button
            type="primary"
            icon={<SearchOutlined />}
            onClick={handleSearch}
          >
            搜索
          </Button>
          <Button icon={<ClearOutlined />} onClick={handleClear}>
            清空
          </Button>
        </div>
      </div>

      {/* 显示已选文件列表 */}
      {selectedFiles.length > 0 && (
        <div style={{ marginBottom: "16px" }}>
          <div style={{ marginBottom: "8px", fontWeight: "500" }}>
            已选择文件 ({selectedFiles.length}个):
          </div>
          <div
            style={{
              display: "flex",
              flexWrap: "wrap",
              gap: "8px",
              padding: "8px",
              backgroundColor: "#f5f5f5",
              borderRadius: "4px",
              maxHeight: "120px",
              overflowY: "auto",
            }}
          >
            {selectedFiles.map((file, index) => (
              <Tag
                key={index}
                closable
                onClose={() => {
                  const newFiles = selectedFiles.filter((_, i) => i !== index);
                  setSelectedFiles(newFiles);
                }}
              >
                {file.name}
              </Tag>
            ))}
          </div>
        </div>
      )}

      {/* 文件列表 */}
      <List
        loading={loading}
        dataSource={fileList}
        pagination={false}
        itemLayout="horizontal"
        renderItem={(item: FileItem) => (
          <List.Item
            actions={[
              <Button
                key="preview"
                type="link"
                icon={<EyeOutlined />}
                onClick={() => handlePreview(item)}
              >
                预览
              </Button>,
              <Button
                key="previewContent"
                type="link"
                icon={<EyeOutlined />}
                onClick={() => handlePreviewContent(item)}
                disabled={!item.fileContent}
              >
                预览局部
              </Button>,
              <Button
                key="download"
                type="link"
                icon={<DownloadOutlined />}
                onClick={() => handleDownload(item)}
              >
                下载
              </Button>,
              <Button
                key="delete"
                type="link"
                danger
                icon={<DeleteOutlined />}
                onClick={() => handleDelete(item.id)}
              >
                删除
              </Button>,
            ]}
          >
            <List.Item.Meta
              title={
                <div>
                  <Space style={{ marginBottom: "4px" }}>
                    <span>{item.fileName}</span>
                    <Tag
                      color={getFileTypeColor(
                        item.fileName.split(".").pop() || ""
                      )}
                    >
                      {item.fileName.split(".").pop()?.toUpperCase()}
                    </Tag>
                  </Space>
                  {item.fileContent && (
                    <div
                      style={{
                        fontSize: "12px",
                        color: "#666",
                        marginTop: "4px",
                        lineHeight: "1.4",
                      }}
                    >
                      {item.fileContent.length > 50
                        ? `${item.fileContent.substring(0, 50)}...`
                        : item.fileContent}
                    </div>
                  )}
                </div>
              }
              description={`路径: ${item.filePath} | 更新时间: ${item.updateTime}`}
            />
          </List.Item>
        )}
      />

      <FilePreview
        visible={previewVisible}
        file={previewFile}
        onClose={() => setPreviewVisible(false)}
        searchText={searchValue.trim() || undefined}
      />

      {/* 文件内容预览弹窗 */}
      <Modal
        title={`文件内容预览 - ${currentFileName}`}
        open={contentModalVisible}
        onCancel={() => setContentModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setContentModalVisible(false)}>
            关闭
          </Button>,
        ]}
        width={1200}
        centered
      >
        <div
          style={{
            maxHeight: "60vh",
            overflowY: "auto",
            padding: "16px",
            backgroundColor: "#f5f5f5",
            borderRadius: "4px",
            whiteSpace: "pre-wrap",
            wordBreak: "break-word",
            lineHeight: "1.6",
            fontSize: "14px",
          }}
        >
          {currentFileContent}
        </div>
      </Modal>
    </div>
  );
};

export default Common;
